#include "QSectionOpertaion.h"

#include "Core/MainWindow.h"
#include "Core/RWGeometryTool.h"
#include <QMessageBox>
#include "FeatureShape/ShapeOperation.h"
#include "FeatureShape/HistoryManager.h"
#include <QComboBox>

QSectionOpertaion::QSectionOpertaion(MainWindow* inMainWindow, ShapeOperation* inOperation, QWidget* parent)
	: QRSWidgetBase(inMainWindow, inOperation, parent)
	, ui(new Ui::QSectionOpertaionClass())
{
	ui->setupUi(this);

	connect(ui->modifyButton, &QPushButton::clicked, this, &QSectionOpertaion::OnModify);
	connect(ui->confirmButton, &QPushButton::clicked, this, &QSectionOpertaion::OnConfirm);
	connect(ui->cancelButton, &QPushButton::clicked, this, &QSectionOpertaion::close);

	connect(m_mainWindow, &MainWindow::OnSelectedActor, this, &QSectionOpertaion::OnSelectedActor);
}

QSectionOpertaion::~QSectionOpertaion()
{
	delete ui;
}

void QSectionOpertaion::closeEvent(QCloseEvent* event)
{
	m_mainWindow->SubWidgetClose(bIsConfirmed);
}

void QSectionOpertaion::OnSelectedActor(Handle(QIVtkSelectionPipeline) actor)
{
	if (actor)
	{
		m_selectedActor = actor.get();
	}
}

void QSectionOpertaion::OnModify()
{
	SectionInner();
	m_selectedActor = nullptr;
}

void QSectionOpertaion::OnConfirm()
{
	SectionInner();
	close();
}

void QSectionOpertaion::SectionInner()
{
	if (!m_selectedActor)
	{
		QMessageBox::warning(this, tr("Warning"), tr("Please select a valid shape."));
		return;
	}

	TopoDS_Shape sectionShape = CreateSectionFromSolid(m_selectedActor->OccShape(), ui->dirCombo->currentIndex());

	if (sectionShape.IsNull())
	{
		QMessageBox::warning(this, tr("Warning"), tr("Section failed."));
		return;
	}

	int shapeIndex = GetIndexFromActor(m_mainWindow->GetCachedActors(), m_selectedActor);

	SectionOperation* op = new SectionOperation(QString("Section"), shapeIndex, ui->dirCombo->currentIndex());
	m_mainWindow->GetHistoryManager()->applyOperation(op);

	m_mainWindow->createBasicUnitActor(sectionShape, true);
}
